#pragma once

#include "mysvg.h"
#include "ui_kososvg.h"
#include "cancvns.h"
#include "mystatusbar.h"

#include <QFileDialog>
#include <QScrollArea>
#include <QKeyEvent>
#include <QDebug>
#include <QEvent>

MySvg::MySvg(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::KosoSvg)
{
    ui->setupUi(this);
    msv = new CanCvns();
    scroll = new QScrollArea(this);
    scroll->setFrameShape(QFrame::NoFrame);
    scroll->setWidget(msv);
    scroll->setAlignment(Qt::AlignCenter);
    mstatusbar = new myStatusbar(this);
    ui->styletoolBar->addWidget(mstatusbar);
    this->setWindowTitle(tr("SVG工具"));
    this->setWindowIcon(QIcon(":/image/SVG.png"));
    setCentralWidget(scroll);
    msv->resetSize(500,500);
    mstatusbar->showsizeInfo(500,500);
    this->resize(600,600);
    mstatusbar->showPensize(3);
    
    // 线程相关设置 - 确保线程安全
    msv->moveToThread(&mCanCvns);
    // 使用Qt::QueuedConnection确保跨线程信号槽安全
    
    // 设置焦点，确保主窗口可以接收键盘事件
    setFocusPolicy(Qt::StrongFocus);
    
    // 安装事件过滤器
    scroll->installEventFilter(this);
    msv->installEventFilter(this);

    //画布传值给工具栏 
    connect(msv, &CanCvns::tobarSizeInfo, mstatusbar, &myStatusbar::showsizeInfo, Qt::QueuedConnection);

    //工具栏传值给画布 
    connect(mstatusbar, &myStatusbar::sizeInfo, msv, &CanCvns::resetSize, Qt::QueuedConnection);
    connect(mstatusbar, &myStatusbar::penSizeInfo, msv, &CanCvns::resetpenSize, Qt::QueuedConnection);
    connect(mstatusbar, &myStatusbar::penstyleInfo, msv, &CanCvns::resetpenStyle, Qt::QueuedConnection);

    // 自动删除线程中的对象
    connect(&mCanCvns, &QThread::finished, msv, &QObject::deleteLater, Qt::QueuedConnection);
}

MySvg::~MySvg()
{
    // 安全停止线程并清理资源
    if (mCanCvns.isRunning()) {
        mCanCvns.quit();
        mCanCvns.wait(); // 等待线程结束
    }
    
    // 如果msv对象未被线程删除（即未启动线程），则手动删除
    if (msv && !mCanCvns.isRunning()) {
        delete msv;
        msv = nullptr;
    }
    
    // 删除其他资源
    delete mstatusbar;
    delete ui;
}

// 实现键盘事件处理
void MySvg::keyPressEvent(QKeyEvent *event)
{
    qDebug() << "主窗口接收到键盘事件: " << event->key();
    
    // 直接调用父类的事件处理函数，先不转发给画布
    QMainWindow::keyPressEvent(event);
}

// 实现事件过滤器
bool MySvg::eventFilter(QObject *watched, QEvent *event)
{
    // 只处理键盘按下事件，忽略其他事件
    if (event->type() != QEvent::KeyPress) {
        return QMainWindow::eventFilter(watched, event);
    }
    
    // 转换为键盘事件
    QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
    int key = keyEvent->key();
    Qt::KeyboardModifiers modifiers = keyEvent->modifiers();
    
    // 如果画布对象不存在，不处理事件
    if (!msv) {
        return QMainWindow::eventFilter(watched, event);
    }
    
    qDebug() << "事件过滤器捕获键盘事件: " << key;
    
    // 使用switch处理按键，比一系列if-else效率更高
    bool handled = true;
    
    // 处理带修饰键的组合键
    if (modifiers == Qt::ControlModifier) {
        switch (key) {
            case Qt::Key_C:
                qDebug() << "处理复制事件";
                msv->onCopyshapeTriggered();
                break;
                
            case Qt::Key_V:
                qDebug() << "处理粘贴事件";
                msv->onPasteshapeTriggered();
                break;
                
            case Qt::Key_A:
                qDebug() << "处理全选事件";
                msv->selectAll();
                break;
                
            case Qt::Key_Z:
                qDebug() << "处理撤销事件";
                msv->undo();
                break;
                
            default:
                handled = false;
                break;
        }
    }
    // 处理单键
    else if (modifiers == Qt::NoModifier) {
        switch (key) {
            case Qt::Key_Delete:
                qDebug() << "处理删除键事件";
                msv->onDeleteshapeTriggered();
                break;
                
            default:
                handled = false;
                break;
        }
    }
    else {
        handled = false;
    }
    
    // 如果事件已处理，则接受事件并返回true
    if (handled) {
        event->accept();
        return true;
    }
    
    // 默认处理
    return QMainWindow::eventFilter(watched, event);
}

void MySvg::on_pen_action_triggered()
{
    msv->change(MyShapeType::freeline);
}

void MySvg::on_line_action_triggered()
{
    msv->change(MyShapeType::line);
}

void MySvg::on_reac_action_triggered()
{
    msv->change(MyShapeType::rect);
}

void MySvg::on_circle_action_triggered()
{
    msv->change(MyShapeType::circle);
}


void MySvg::on_hexagon_action_triggered()
{
    msv->change(MyShapeType::pentagon);
}

void MySvg::on_triangle_action_triggered()
{
    msv->change(MyShapeType::trangle);
}
void MySvg::on_text_action_triggered()
{
    msv->change(MyShapeType::text);
}

void MySvg::on_open_action_triggered()
{
    QString filename = QFileDialog::getOpenFileName(this,tr("打开"),"/","svg files(*.svg)");
    if (filename.isEmpty())
        return;
    msv->loadSvgFile(filename);
}

void MySvg::on_save_action_triggered()
{
    QString newPath = QFileDialog::getSaveFileName(this, tr("Save SVG"),"/", tr("SVG files (*.svg)"));
    if (newPath.isEmpty())
        return;
    msv->saveSvgFile(newPath);
}

void MySvg::on_pencolor_action_triggered()
{
    msv->setPencolor();
}

void MySvg::on_backColor_action_triggered()
{
    msv->setBackcolor();
}

void MySvg::on_fill_action_triggered()
{
    msv->setFillcolor();
}

void MySvg::on_selector_action_triggered()
{
    msv->setDragable();
}


void MySvg::on_clear_action_triggered()
{
    msv->clearCvns();
}

void MySvg::on_new_action_triggered()
{
    msv->newCvns();
}
